import path from 'node:path'
import Vue from '@vitejs/plugin-vue'

import Unocss from 'unocss/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import VueRouter from 'unplugin-vue-router/vite'

import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '~/': `${path.resolve(__dirname, 'src')}/`,
    },
  },
  // 添加server配置以允许外部访问
  server: {
    host: '0.0.0.0', // 允许外部访问
    port: 5173, // 端口号，可根据需要修改
    open: false, // 不自动打开浏览器
    cors: true, // 允许跨域请求
    proxy: {
      // 匹配所有以 '/api' 开头的请求
      '/api': {
        target: 'http://127.0.0.1:8081', // 后端API地址
        changeOrigin: true, // 允许跨域
        rewrite: path => path.replace(/^\/api/, ''), // 移除路径中的 '/api' 前缀
      },
      '/static': {
        target: 'http://127.0.0.1:8081', // 后端API地址
        changeOrigin: true, // 允许跨域
        rewrite: path => path, // 移除路径中的 '/api' 前缀
      },
    },
  },

  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "~/styles/element/index.scss" as *;`,
        api: 'modern-compiler',
      },
    },
  },

  plugins: [
    Vue(),

    // https://github.com/posva/unplugin-vue-router
    VueRouter({
      extensions: ['.vue', '.md'],
      dts: 'src/typed-router.d.ts',
    }),

    Components({
      // allow auto load markdown components under `./src/components/`
      extensions: ['vue', 'md'],
      // allow auto import and register components used in markdown
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
      resolvers: [
        ElementPlusResolver({
          importStyle: 'sass',
        }),
      ],
      dts: 'src/components.d.ts',
    }),

    // https://github.com/antfu/unocss
    // see uno.config.ts for config
    Unocss(),
  ],

  ssr: {
    // TODO: workaround until they support native ESM
    noExternal: ['element-plus'],
  },
})
